<template>
  <div class="main">
    <!-- logo图标 -->
    <div class="logo-icon">
      <img class="logo-img" alt="" :src="imgSrc" />
    </div>
    <input type="text" class="search-inp" v-model="inpText" ref="inp" placeholder="点击此处进行搜索" @input="getFocus"
      @keydown="searchIt" @blur="getBlur" @focus="showSug" />
    <div class="suggest" v-show="isShowSug">
      <div v-for="(suggestion, index) in suggestions" :key="index" @click="handleClick(suggestion)"
        :class="{ 'selected': index === selectedIndex }">
        <div>{{ suggestion }}</div>
      </div>
    </div>
    <select class="select" @change="changeSearchEngine">
      <option value="Bing">Bing</option>
      <option value="Baidu">Baidu</option>
      <option value="Google">Google</option>
    </select>
  </div>
</template>

<script setup>
import { onMounted, ref, nextTick } from "vue";
import { debounce } from "lodash";
import { useStore } from "@/stores/counter";
const store = useStore();
let browerType = ref("Bing");
let inpText = ref("");
let suggestions = ref([]);
let isShowSug = ref(false);
const inp = ref(null);
//展示当前默认展示的index
const selectedIndex = ref(-1);

let imgSrc = ref(
  "https://ts1.cn.mm.bing.net/th?id=ODLS.be51c863-330b-438b-bf0f-ea99978c5aeb&w=32&h=32&qlt=94&pcl=fffffa&o=6&pid=1.2"
);
//切换搜索引擎
const changeSearchEngine = (e) => {
  browerType.value = e.target.value;
  if (e.target.value === "Bing") {
    imgSrc.value =
      "https://ts1.cn.mm.bing.net/th?id=ODLS.be51c863-330b-438b-bf0f-ea99978c5aeb&w=32&h=32&qlt=94&pcl=fffffa&o=6&pid=1.2";
  } else if (e.target.value === "Baidu") {
    imgSrc.value =
      "https://ts3.cn.mm.bing.net/th?id=ODLS.b689dae1-edfb-4adf-aad6-fbef599f8e14&w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2";
  } else if (e.target.value === "Google") {
    imgSrc.value =
      "https://ts4.cn.mm.bing.net/th?id=ODLS.79d7c869-d108-4a09-965b-6f9cfe1c079d&w=32&h=32&qlt=90&pcl=fffffa&o=6&pid=1.2";
  }
};
//回车进行搜索
const searchIt = (e) => {
  if (e.keyCode === 13) {
    if (browerType.value === "Bing") {
      const url = `https://cn.bing.com/search?q=${inpText.value}`;
      window.open(url, "_blank");
    } else if (browerType.value === "Baidu") {
      const url = `https://www.baidu.com/s?wd=${inpText.value}`;
      window.open(url, "_blank");
    } else if (browerType.value === "Google") {
      const url = `https://www.google.com/search?q=${inpText.value}`;
      window.open(url, "_blank");
    }
  } else if (e.key === 'ArrowUp') {
    // 向上箭头键
    if (selectedIndex.value > 0) {
      selectedIndex.value--;
      inpText.value = suggestions.value[selectedIndex.value];
      //使焦点放到输入框文字末尾
      setTimeout(() => {
        inp.value.focus();
        inp.value.setSelectionRange(inp.value.value.length, inp.value.value.length);
      }, 10);
    } else if (selectedIndex.value == 0) {
      inpText.value = store.curText;
      selectedIndex.value--;
      setTimeout(() => {
        inp.value.focus();
        inp.value.setSelectionRange(inp.value.value.length, inp.value.value.length);
      }, 10);
    } else {
      selectedIndex.value = -1;

    }

  } else if (e.key === 'ArrowDown') {
    // 向下箭头键
    if (selectedIndex.value < suggestions.value.length - 1) {
      selectedIndex.value++;
      inpText.value = suggestions.value[selectedIndex.value];
    } else {
      // 如果是最后一项，回到第一项
      selectedIndex.value = -1;
    }
  }

};
//获取焦点事件
const getFocus = () => {
  store.saveCurText(inpText.value);
  selectedIndex.value = -1;
  //发送请求获取建议
  showSug();
};
const showSug = () => {
  getData();
  debounce(() => {
    isShowSug.value = true;
  }, 500)();
}
//失去焦点事件
const getBlur = () => {
  debounce(() => {
    isShowSug.value = false;
  }, 200)();
};
//请求api接口获取建议数据
const getData = () => {
  // 创建一个<script>标签并设置src属性为跨域请求的URL
  const script = document.createElement("script");
  if (browerType.value === "Bing") {
    script.src = `http://api.bing.com/qsonhs.aspx?type=cb&q=${inpText.value == "" ? "" : inpText.value
      }&cb=callback`;
  } else if (browerType.value === "Baidu") {
    script.src = `http://suggestion.baidu.com/su?wd=${inpText.value == "" ? "" : inpText.value
      }&cb=callback`;
  } else if (browerType.value === "Google") {
    script.src = `http://suggestqueries.google.com/complete/search?client=youtube&q=${inpText.value == "" ? "" : inpText.value
      }&cb=callback`;
  }
  document.body.appendChild(script);

  // 请求完成后移除<script>标签
  script.onload = () => {
    document.body.removeChild(script);
  };
};
//jsonp请求的回调函数
window.callback = (data) => {
  if (browerType.value === "Baidu") {
    if (data.s.length == 0) {
      isShowSug.value = false;
    } else {
      suggestions.value = data.s;
      isShowSug.value = true;
    }
  } else if (browerType.value === "Bing") {
    //获取bing搜索推荐
    const res = data.AS.Results;
    if (res == undefined) {
      console.log('无搜索建议！');
    } else {
      if (res.length > 0) {
        const sug1 = res[0] ? res[0].Suggests : [];
        const sug2 = res[1] ? res[1].Suggests : [];
        let sugArr = sug1.concat(sug2);
        const sugData = sugArr.map((item) => {
          return item.Txt;
        });
        if (sugData.length == 0) {
          isShowSug.value = false;
        } else {
          suggestions.value = sugData;
          isShowSug.value = true;
        }
      }
    }
  } else if (browerType.value === "Google") {
    console.log("待添加");
  }
};
const handleClick = (suggestion) => {
  // 在点击时跳转到指定页面
  if (browerType.value === "Bing") {
    inpText.value = suggestion;
    const url = `https://cn.bing.com/search?q=${suggestion}`;
    window.open(url, "_blank");
  } else if (browerType.value === "Baidu") {
    inpText.value = suggestion;
    const url = `https://www.baidu.com/s?wd=${suggestion}`;
    window.open(url, "_blank");
  } else if (browerType.value === "Google") {
    inpText.value = suggestion;
  }
  isShowSug.value = false;
};
onMounted(() => {
  inp.value.focus();
})
</script>

<style scoped>
.main {
  flex: 5;
  display: flex;
  justify-content: center;
}

/* 搜索框样式 */
.search-inp {
  width: 30vw;
  height: 3vw;
  border-radius: 4vw;
  appearance: none;
  outline: none;
  background: transparent;
  font-size: 18px;
  font-family: "Gill Sans", sans-serif;
  padding-left: 3.6667vw;
  padding-right: 5.3333vw;
  border: none;
  background-color: #fff;
}

.search-inp:hover {
  box-shadow: 2px 2px 2px 2px rgba(0, 0, 0, 0.05),
    0 2px 4px 1px rgba(0, 0, 0, 0.2);
}

/* 搜索提示框 */
.suggest {
  padding: 2px;
  position: absolute;
  top: 28.666vh;
  left: 29.33vw;
  width: 39.333vw;
  background-color: #fff;
  border-radius: 1vw;
  display: flex;
  flex-direction: column;
}

.suggest>div {
  border-radius: 1vw;
  height: 5vh;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  text-indent: 10px;
  font-size: 18px;
  font-family: "Gill Sans", sans-serif;
}

.suggest>div:hover {
  background-color: #ececec;
  cursor: pointer;
}

/* logo */
.logo-icon {
  position: relative;
  left: 3vw;
  top: 0.2667vw;
  width: 2.6667vw;
  height: 2.6667vw;
  border-radius: 30%;
  line-height: 2.4vw;
  display: flex;
  justify-content: center;
  align-items: center;
}

/* logo大小 */
.logo-img {
  width: 1.6666vw;
  height: 1.6666vw;
  margin-bottom: 0.15vw;
}

/* 选择框样式 */
.select {
  cursor: pointer;
  position: relative;
  right: 5vw;
  top: 0.2667vw;
  width: 4.6667vw;
  height: 2.637vw;
  border-radius: 20px;
  line-height: 2.4vw;
  padding-bottom: 5px;
  border: none;
  outline: none;
  font-size: 18px;
  -webkit-appearance: none;
  -moz-appearance: none;
  text-align: center;
  background: url("../assets/arrow3.png") no-repeat right center;
  appearance: none;
  font-weight: 200;
  font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
  color: rgb(86, 92, 99);
}

.selected {
  background-color: #ececec;
  cursor: pointer;
}
</style>
